﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using Furion;
using Furion.DatabaseAccessor;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using YBlog.Application;
using YBlog.EntityFramework.Core.FreeSqlUtils;

namespace YBlog.AgileDevelop.DatabaseManagement
{
    /// <summary>
    /// 数据库
    /// </summary>
    [ApiDescriptionSettings("AgileDevelop")]
    public class DataBaseService : IBaseService
    {
        private readonly IFreeSql _freeSql;
        private readonly IMemoryCacheService _memoryCache;

        public DataBaseService(IFreeSql freeSql, IMemoryCacheService memoryCache)
        {
            _freeSql = freeSql;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取数据库名
        /// </summary>
        /// <returns></returns>
        public List<string> GetDataBase()
        {
            return _freeSql.DbFirst.GetDatabases();
        }
        /// <summary>
        /// 获取表
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public DaTableInfoDto GetTable(string tableName)
        {
            var type = App.EffectiveTypes.FirstOrDefault(t => 
            typeof(IEntity).IsAssignableFrom(t)
            && t.IsClass 
            && !t.IsAbstract 
            && !t.IsGenericType 
            && !t.IsInterface 
            && !t.IsDefined(typeof(NonAutomaticAttribute), true)
            && (
                t.Name.Equals(tableName,StringComparison.OrdinalIgnoreCase)  
                || tableName.Equals(t.GetCustomAttribute<TableAttribute>(true)?.Name, StringComparison.OrdinalIgnoreCase)
                )
            );
            if (type == null)
                return null;
            return _freeSql
                .DbFirst
                .GetTableByName(
                    type.GetCustomAttribute<TableAttribute>()?.Name ?? type.Name
                )
                .Adapt<DaTableInfoDto>();
        }
        /// <summary>
        /// 获取所有表
        /// </summary>
        /// <returns></returns>
        public List<DaTableInfoDto> GetTableList()
        {
            var entityCorrelationTypes = App.EffectiveTypes.Where(t => 
                typeof(IEntity).IsAssignableFrom(t)
                && t.IsClass 
                && !t.IsAbstract 
                && !t.IsGenericType 
                && !t.IsInterface 
                && !t.IsDefined(typeof(NonAutomaticAttribute), true)
                )
                .ToList();
            var dbInfoList = new List<DaTableInfoDto>();
            foreach(var type in entityCorrelationTypes) 
            {
                dbInfoList.Add(
                    _freeSql
                    .DbFirst
                    .GetTableByName(
                        type.GetCustomAttribute<TableAttribute>()?.Name ?? type.Name
                     )
                    .Adapt<DaTableInfoDto>());
            }
            return dbInfoList;
        }

        /// <summary>
        /// 同步数据库结构
        /// </summary>
        public void AutoSyncDataStructure()
        {
            _memoryCache.Clear();
            FreeSqlHelper.AutoSyncDataStructure(_freeSql);
        }

        /// <summary>
        /// 重载种子数据
        /// </summary>
        public void ReloadSeedData()
        {
            _memoryCache.Clear();
            FreeSqlHelper.ReloadSeedData(_freeSql);

        }
    }
}
